from component import *
import pyglet
from pyglet.gl import *
from pyglet.window import key

import graphics2d
import data
from timer import *

from math import *

class Robot(object):
	"""something that holds components together"""
	def __init__(self,keys,firstComponent=None,x=0.0,y=0.0,rotation=0.0):
		super(Robot, self).__init__()
		self.keys=keys
		self.components=[]
		self.keyTable = {}
		
		self.mass = 0
		if firstComponent != None:
			self.addComponent(firstComponent,key.RIGHT)
		
		self.position = (x,y)
		self.rotation=rotation
		self.rotSpeed = 0.0
		self.rotAccel = 0.0
		self.velocity = (0.0,0.0)
		self.accel = (0.0,0.0)
		
	def addComponent(self, comp, k):		
		comp.parent = self
		self.components.append(comp)
		self.mass += comp.mass
		if k in self.keyTable:
			self.keyTable[k].append(comp)
		else:
			self.keyTable[k] = [comp]
	def bindKey(self, comp, k):
		if k in self.keyTable:
			self.keyTable[k].append(comp)
		else:
			self.keyTable[k] = [comp]
	def applyTorque(self, F, r, theta):
		self.rotAccel += F*40*sin(radians(theta))/(self.mass*r)
	def applyForce(self, F, r, theta):
		self.accel = (self.accel[0]+F*cos(radians(self.rotation+theta+90))/self.mass, self.accel[1]+F*sin(radians(self.rotation+theta+90))/self.mass)
	def update(self):
		for k in self.keyTable:
			#print k, compList
			if self.keys[k]:
				for comp in self.keyTable[k]:
					comp.act()
		self.velocity = (self.velocity[0] + self.accel[0]*timer.dt, self.velocity[1] + self.accel[1]*timer.dt)
		self.position = (self.position[0] + self.velocity[0]*timer.dt, self.position[1] + self.velocity[1]*timer.dt)
		self.accel = (0.0,0.0)
		self.rotSpeed += self.rotAccel*timer.dt
		self.rotation += self.rotSpeed*timer.dt
		#print self.rotation
		self.rotAccel = 0.0
		
		if self.position[0] < -80:
			self.position = (self.position[0]+data.assets.width+160,self.position[1])
		if self.position[1] < -80:
			self.position = (self.position[0],self.position[1]+data.assets.height+160)
		if self.position[0] > data.assets.width+80:
			self.position = (self.position[0]-data.assets.width-160,self.position[1])
		if self.position[1] > data.assets.height+80:
			self.position = (self.position[0],self.position[1]-data.assets.height-160)
	def draw(self):
		glPushMatrix()
		glTranslatef(self.position[0],self.position[1],0.0)
		glRotatef(self.rotation, 0, 0, 0.1)
		graphics2d.draw_line(-30,0,30,0)
		graphics2d.draw_line(0,0,0,30)
		for c in self.components:
			c.draw()
		glPopMatrix()